package services

import (
	"context"
	"encoding/json"
	"errors"
	"lingc/models"
	"lingc/utils"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// SysConfigService 提供账号登录校验的服务
type SysConfigService struct {
	DB *gorm.DB
}

const configCahceKey = "sys_config_data"

// NewSysConfigService 创建一个新的 SysConfigService 实例
func NewSysConfigService(db *gorm.DB) *SysConfigService {
	return &SysConfigService{DB: db}
}

//表单业务

/**
 * @Description: 分页获取列表
 * @param where
 * @param page
 * @param pageSize
 * @return []*models.SysConfig
 * @return int
 * @return int64
 * @return error
 */
func (s *SysConfigService) PageSysConfigList(where string, page, pageSize int) ([]*models.SysConfigList, int, int64, error) {
	var groups []*models.SysConfig
	var total int64

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 获取总记录数
	if err := s.DB.Model(&models.SysConfig{}).Where(where).Count(&total).Error; err != nil {
		return nil, 1, 0, err
	}

	// 获取分页数据
	if err := s.DB.Where(where).Offset(offset).Limit(pageSize).Order("id DESC").Find(&groups).Error; err != nil {
		return nil, 1, 0, err
	}
	var list []*models.SysConfigList
	list = []*models.SysConfigList{}
	for _, data := range groups {
		list = append(list, &models.SysConfigList{
			ID:        data.ID,
			Name:      data.Name,
			Key:       data.Key,
			Value:     data.Value,
			AppID:     data.AppID,
			CreatedAt: time.Unix(data.CreatedAt, 0).Format("2006-01-02 15:04:05"), // 格式化时间戳
			UpdatedAt: time.Unix(data.UpdatedAt, 0).Format("2006-01-02 15:04:05"), // 格式化时间戳
		})
	}

	return list, page, total, nil
}

/**
 * @Description: 创建新
 * @param username
 * @param password
 * @param realname
 * @param avatar
 * @param status
 * @return *models.SysConfigCreate
 * @return error
 */
func (s *SysConfigService) CreateSysConfig(data *models.SysConfigCreate) (*models.SysConfigCreate, error) {
	// 检查是否已存在
	var existingData models.SysConfig
	if err := s.DB.Where("key = ?", data.Key).First(&existingData).Error; err == nil {
		return nil, errors.New("数据已存在")
	}
	addData := &models.SysConfig{
		Name:      data.Name,
		Key:       data.Key,
		Value:     data.Value,
		AppID:     data.AppID,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	// 保存到数据库
	if err := s.DB.Create(addData).Error; err != nil {
		return nil, err
	}
	return data, nil
}

// GetSysConfig 获取信息
func (s *SysConfigService) GetSysConfig(where string) (*models.SysConfig, error) {
	var data models.SysConfig
	if err := s.DB.Where(where).First(&data).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("数据不存在")
		}
		return nil, err
	}
	// log.Printf("data_info:%v", data)
	return &data, nil
}

// GetSysConfigData 获取信息
func (s *SysConfigService) GetSysConfigData(c *gin.Context) (map[string]interface{}, error) {

	data_info_json := NewSysConfigService(utils.MysqlClient).GetCahceConfig(c)
	if data_info_json != nil {
		return data_info_json, nil
	}
	var data []*models.SysConfig
	if err := s.DB.Find(&data).Error; err != nil {
		return nil, err
	}
	data_info := make(map[string]interface{})
	for _, item := range data {
		data_info[item.Key] = item.Value
	}
	NewSysConfigService(utils.MysqlClient).SetCahceConfig(data_info, c)
	return data_info, nil
}

// SetCahceConfig 设置缓存
func (s *SysConfigService) SetCahceConfig(data map[string]interface{}, c *gin.Context) error {

	dataJson, err := json.Marshal(data)
	if err != nil {
		return err
	}
	utils.SetRedis(configCahceKey, dataJson, 24*60)
	return nil
}

// SetCahceConfig 获取缓存
func (s *SysConfigService) GetCahceConfig(c *gin.Context) map[string]interface{} {

	dataJson := utils.GetRedis(configCahceKey)
	if dataJson != "" {
		data_info := make(map[string]interface{})
		err := json.Unmarshal([]byte(dataJson), &data_info)
		if err != nil {
			return nil
		}
		return data_info
	}
	return nil
}

// 删除缓存
func (s *SysConfigService) DelCahceConfig(c *gin.Context) error {

	utils.RedisClient.Del(context.Background(), configCahceKey)
	return nil
}

/**
 * @Description: 更新信息
 * @param data
 * @return error
 */
func (s *SysConfigService) UpdateSysConfig(data *models.SysConfigUpdate) (*models.SysConfigUpdate, error) {
	// 检查名是否已存在
	var existingData models.SysConfig
	if err := s.DB.Where("id = ?", data.ID).First(&existingData).Error; err != nil {
		return nil, errors.New("数据不存在")
	}
	existingData.Name = data.Name
	existingData.Key = data.Key
	existingData.Value = data.Value
	existingData.UpdatedAt = time.Now().Unix()
	return data, s.DB.Save(existingData).Error
}

/**
 * @Description: 删除
 * @param id
 * @return error
 */
func (s *SysConfigService) DeleteSysConfig(id uint) error {
	var data models.SysConfig
	if err := s.DB.Where("id = ?", id).First(&data).Error; err != nil {
		return errors.New("数据不存在")
	}
	return s.DB.Delete(&data).Error
}

/**
 * @Description: 批量删除
 * @param id
 * @return error
 */
func (s *SysConfigService) DeleteSysConfigs(ids []string) error {
	for _, id := range ids {
		var data models.SysConfig
		if err := s.DB.Where("id = ?", id).First(&data).Error; err != nil {
			return errors.New("数据不存在")
		}
		err := s.DB.Delete(&data).Error
		if err != nil {
			return errors.New("删除失败")
		}
	}
	return nil
}
